﻿using System.Windows.Threading;
using System.Xml.Linq;
using C1.Phone;
using Microsoft.Phone.Shell;
using SMARTMobile.Common;
using SmartMobile.Data;
using SMARTMobile.Models;
using SMARTMobile.Framework;
using SMARTMobile.Models.Local;
using SMARTMobile.Models.Xml;
using SMARTMobile.Services.SMARTMobileServiceReference;
using SMARTMobile.WinPhone;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using Microsoft.Phone.Controls;
using SmartMobile.Data;
using System.IO;
using System.Data.Linq;
using System.Collections.ObjectModel;

namespace SMARTMobile.ViewModels
{
    public enum ReaderWithoutWhereType
    {
        NONE,
        PhoneVendor,
        PriceRange,
        OutletVendor,
        OutdoorType,
        InDoorType,
        NokiaMerchandisingType,
        NokiaPG,
        OutletAdvanceInforListing,
        OutletAdvanceInforTable,
        END,
        FINISH,
    }

    public enum ReaderWithWhereFieldType
    {
        NONE,
        ImageType,
        City,
        Area,
        Region,
        GFKArea,
        Tier,
        Operators,
        END,
    }

    public partial class NhanThongTinViewModel : ViewModelBase
    {
        private bool _isCustomer;
        private bool _isProvince;
        private int _progress = 0;
        private int _checkBusy = 1;
        private bool _isNhanVien;
        private bool _isGiamSat;

        private bool _getProvinceCompleted = false;
        private bool _getTownCompleted = false;
        private bool _getCustomerCompleted = false;
        private bool _getReaderwhithwhereCompleted = false;
        private ReaderWithoutWhereType _currentType;
        private ReaderWithWhereFieldType _currentWithWhereType;

        SmartMobileDBContext _smartMobileContext;
        private ReloadDataSmartPhoneSoapClient _proxy;
        private bool _isOnGettingCustomer;

        public NhanThongTinViewModel()
        {
            this.CreateConnection();
            _currentType = ReaderWithoutWhereType.NONE;
            _currentWithWhereType = ReaderWithWhereFieldType.NONE;
            this.ExitCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteExitCommand
            };

            this.UpdateCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteUpdateCommand
            };

            if (GlobalInformation.ArSaleSPType.Usertype == "SS")
            {
                this.IsNhanVien = false;
                this.IsGiamSat = true;
            }
            else
            {
                this.IsNhanVien = true;
                this.IsGiamSat = false;
            }
        }

        public bool IsGiamSat
        {
            get { return this._isGiamSat; }
            set
            {
                this._isGiamSat = value;
                base.RaisePropertyChanged("IsGiamSat");
            }
        }

        public bool IsNhanVien
        {
            get { return this._isNhanVien; }
            set
            {
                this._isNhanVien = value;
                base.RaisePropertyChanged("IsNhanVien");
            }
        }

        public bool IsCustomer
        {
            get
            {
                return this._isCustomer;
            }
            set
            {
                this._isCustomer = value;
                RaisePropertyChanged("IsCustomer");
            }
        }

        public bool IsProvince
        {
            get
            {
                return this._isProvince;
            }
            set
            {
                this._isProvince = value;
                RaisePropertyChanged("IsProvince");
            }
        }

        #region Command

        public ICommandRoute ExitCommand
        {
            get;

            private set;
        }

        public ICommandRoute UpdateCommand
        {
            get;

            private set;
        }

        public ReloadDataSmartPhoneSoapClient Proxy
        {
            get
            {
                if (_proxy == null)
                {
                    _proxy = new ReloadDataSmartPhoneSoapClient(GlobalInformation.Binding, GlobalInformation.Endpoint);
                }

                return _proxy;
            }
            set { _proxy = value; }
        }

        #endregion

        #region Command Action Handlers

        private void ExecuteUpdateCommand(object commandParams)
        {
            try
            {
                if (string.IsNullOrEmpty(GlobalInformation.ArSaleSPType.Sitecode))
                {
                    this.UpdateCommand.RaiseCanExecuteChanged(true);
                    this.ShowMessage("Vui lòng chọn Công Ty.");
                    return;
                }

                if (IsCustomer && IsProvince)
                {
                    this.IsBusy = true;

                    if (GlobalInformation.ArSaleSPType.Usertype == "DSR")
                    {
                        this._proxy.GetCustomerAsync(GlobalInformation.ArSaleSPType.Usercode, GlobalInformation.ArSaleSPType.Usertype, GlobalInformation.ArSaleSPType.Sitecode, "2");
                        _currentWithWhereType = ReaderWithWhereFieldType.ImageType;
                        this.Proxy.GetReaderwhithwhereAsync("", "1", "ImageType", "status = 1");
                        this.Proxy.GetProvinceAsync(GlobalInformation.SiteCode);
                        this.Proxy.GetTownAsync(GlobalInformation.SiteCode);
                        this._progress = 3;
                    }
                    else
                    {
                        // Lay thong tin theo giam sat 
                        this.Proxy.GetCustomerAsync(GlobalInformation.ArSaleSPType.Usercode, GlobalInformation.ArSaleSPType.Usertype, GlobalInformation.ArSaleSPType.Sitecode, "2");
                        _currentWithWhereType = ReaderWithWhereFieldType.ImageType;
                        this.Proxy.GetReaderwhithwhereAsync("", "1", "ImageType", "status = 1");
                        this.Proxy.GetProvinceAsync(GlobalInformation.SiteCode);
                        this.Proxy.GetTownAsync(GlobalInformation.SiteCode);
                        this._progress = 3;
                    }

                    this._isOnGettingCustomer = true;
                }
                else
                {
                    if (IsProvince)
                    {
                        this.IsBusy = true;
                        this.Proxy.GetProvinceAsync(GlobalInformation.SiteCode);
                        this.Proxy.GetTownAsync(GlobalInformation.SiteCode);
                        this._progress = 2;
                    }

                    if (IsCustomer)
                    {
                        this.IsBusy = true;
                        if (GlobalInformation.ArSaleSPType.Usertype == "DSR")
                        {
                            this.Proxy.GetCustomerAsync(GlobalInformation.ArSaleSPType.Usercode, GlobalInformation.ArSaleSPType.Usertype, GlobalInformation.ArSaleSPType.Sitecode, "2");

                            this.Proxy.GetReaderwhithwhereAsync("", "1", "ImageType", "status = 1");

                            this._progress = 1;
                        }
                        else
                        {
                            // Lay thong tin theo giam sat
                            this.Proxy.GetCustomerAsync(GlobalInformation.ArSaleSPType.Usercode, GlobalInformation.ArSaleSPType.Usertype, GlobalInformation.ArSaleSPType.Sitecode, "2");

                            this.Proxy.GetReaderwhithwhereAsync("", "1", "ImageType", "status = 1");
                            this._progress = 1;
                        }

                        this._isOnGettingCustomer = true;
                    }

                    if (IsCustomer == false && IsProvince == false)
                    {
                        this.ShowMessage("Vui lòng chọn mục muốn lấy dữ liệu");
                        this.UpdateCommand.RaiseCanExecuteChanged(true);
                    }
                }
            }
            catch (Exception)
            {
                this.IsBusy = false;
                this.UpdateCommand.RaiseCanExecuteChanged(true);
                throw;
            }
        }

        private void ExecuteExitCommand(object commandParams)
        {
            this.ExitCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("Main");
        }

        public override void PageLoaded(Uri uri)
        {
            this.Proxy.GetProvinceCompleted += this.Proxy_GetProvinceCompleted;
            this.Proxy.GetTownCompleted += this.Proxy_GetTownCompleted;
            this.Proxy.GetCustomerCompleted += this.Proxy_GetCustomerCompleted;
            this.Proxy.GetReaderwhithwhereCompleted += Proxy_GetReaderwhithwhereCompleted;
            this.Proxy.GetReaderwhithoutewhereCompleted += Proxy_GetReaderwhithoutewhereCompleted;
        }

        public override void PageUnloaded(Uri uri)
        {
            this.Proxy.GetProvinceCompleted -= this.Proxy_GetProvinceCompleted;
            this.Proxy.GetTownCompleted -= this.Proxy_GetTownCompleted;
            this.Proxy.GetCustomerCompleted -= this.Proxy_GetCustomerCompleted;
            this.Proxy.GetReaderwhithwhereCompleted -= Proxy_GetReaderwhithwhereCompleted;
            this.Proxy.GetReaderwhithoutewhereCompleted -= Proxy_GetReaderwhithoutewhereCompleted;
        }

        private void CreateConnection()
        {
            this._smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);
            this._smartMobileContext.CreateIfNotExists();
        }
        #endregion

        #region Web-service Event Handlers

        private void Proxy_GetCustomerCompleted(object sender, GetCustomerCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // serializes the XML data to Object
                List<XmlARCUST> TCARCUSTs = XmlHelper.GetItems<XmlARCUST>(e.Result.Nodes[1], "Table").ToList();

                // Delete data before insert 
                _smartMobileContext.TCARCUST.DeleteAllOnSubmit(_smartMobileContext.TCARCUST.ToList());
                _smartMobileContext.ARCUST.DeleteAllOnSubmit(_smartMobileContext.ARCUST.ToList());
                _smartMobileContext.SubmitChanges();

                // converts to savable object-list
                foreach (XmlARCUST arcust in TCARCUSTs)
                {
                    //localARSaleSP 
                    ARCUST localARCUST = new ARCUST();
                    localARCUST.ID_PK = Guid.NewGuid();
                    localARCUST.Customername = arcust.customername;
                    localARCUST.Customerkey = arcust.customerkey;
                    localARCUST.Address = arcust.address;
                    localARCUST.Lat = arcust.Lat.ToString();
                    localARCUST.Long = arcust.Long.ToString();
                    localARCUST.Ward = arcust.Ward;
                    localARCUST.Street = arcust.Street;
                    localARCUST.Provice = arcust.ProvinceCode;
                    _smartMobileContext.ARCUST.InsertOnSubmit(localARCUST);

                    TCARCUST localTCARCUST = new TCARCUST();
                    localTCARCUST.ID_PK = Guid.NewGuid();
                    localTCARCUST.Phone = arcust.phone;
                    localTCARCUST.Customername = arcust.customername;
                    localTCARCUST.Customerkey = arcust.customerkey;
                    localTCARCUST.Address = arcust.address;
                    localTCARCUST.Lat = arcust.GPSH.ToString();
                    localTCARCUST.Long = arcust.GPSV.ToString();
                    localTCARCUST.Ward = arcust.Ward;
                    localTCARCUST.Street = arcust.Street;
                    localTCARCUST.Provice = arcust.ProvinceCode;
                    localTCARCUST.Salespkey = arcust.salepersonkey;
                    localTCARCUST.DeliveryAddress = arcust.DeliveryAddress;
                    localTCARCUST.T2 = arcust.T2 ? "1" : "0";
                    localTCARCUST.T3 = arcust.T3 ? "1" : "0";
                    localTCARCUST.T4 = arcust.T4 ? "1" : "0";
                    localTCARCUST.T5 = arcust.T5 ? "1" : "0";
                    localTCARCUST.T6 = arcust.T6 ? "1" : "0";
                    localTCARCUST.T7 = arcust.T7 ? "1" : "0";
                    localTCARCUST.FindField = arcust.FindField;
                    localTCARCUST.ShopOwner = arcust.customername;
                    _smartMobileContext.TCARCUST.InsertOnSubmit(localTCARCUST);
                }

                _smartMobileContext.SubmitChanges();

                this._getCustomerCompleted = true;

                this.CheckBusy();

                TCARCUST arcus = this._smartMobileContext.TCARCUST.FirstOrDefault();
                if (arcus == null)
                {
                    MessageBox.Show("Không thể cập nhật dữ liệu vui lòng kiểm tra thông tin người dùng");
                }
            }
            else
            {
                base.IsBusy = false;
                MessageBox.Show("Có lỗi xảy ra trong quá trình đồng bộ dữ liệu.\n Vui lòng thử lại sau");
                this.UpdateCommand.RaiseCanExecuteChanged(true);
            }
        }

        private void Proxy_GetReaderwhithoutewhereCompleted(object sender, GetReaderwhithoutewhereCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                try
                {
                    switch (_currentType)
                    {
                        case ReaderWithoutWhereType.PhoneVendor:
                            {
                                List<XmlPhoneVendor> phoneVendors =
                                    XmlHelper.GetItems<XmlPhoneVendor>(e.Result.Nodes[1], "Table").ToList();

                                // Delete data before insert 
                                _smartMobileContext.PhoneVendor.DeleteAllOnSubmit(_smartMobileContext.PhoneVendor.ToList());
                                _smartMobileContext.SubmitChanges();

                                PhoneVendor localObject = null;

                                // converts to savable object-list
                                foreach (XmlPhoneVendor item in phoneVendors)
                                {
                                    localObject = new PhoneVendor
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        PhoneVendorName = item.PhoneVendorName,
                                        PhoneVendorCode = item.PhoneVendorCode,
                                        Active = item.Active,
                                        IsOperator = item.IsOperator
                                    };

                                    _smartMobileContext.PhoneVendor.InsertOnSubmit(localObject);
                                }

                                _smartMobileContext.SubmitChanges();
                                _currentType = ReaderWithoutWhereType.PriceRange;
                                this.Proxy.GetReaderwhithoutewhereAsync("", "1", "PriceRange", "");
                                break;
                            }
                        case ReaderWithoutWhereType.PriceRange:
                            {
                                List<XmlPriceRange> priceRanges =
                                    XmlHelper.GetItems<XmlPriceRange>(e.Result.Nodes[1], "Table").ToList();

                                // Delete data before insert 
                                _smartMobileContext.PriceRange.DeleteAllOnSubmit(_smartMobileContext.PriceRange.ToList());
                                _smartMobileContext.SubmitChanges();

                                PriceRange localObject = null;

                                // converts to savable object-list
                                foreach (XmlPriceRange item in priceRanges)
                                {
                                    localObject = new PriceRange
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        PriceRangeCode = item.PriceRangeCode,
                                        Descriptionn = item.Descriptionn,
                                        Active = item.Active
                                    };

                                    _smartMobileContext.PriceRange.InsertOnSubmit(localObject);
                                }

                                _smartMobileContext.SubmitChanges();
                                _currentType = ReaderWithoutWhereType.OutletVendor;
                                this.Proxy.GetReaderwhithoutewhereAsync("", "1", "OutletVendor", "");
                                break;
                            }

                        case ReaderWithoutWhereType.OutletVendor:
                            {
                                List<XmlOutletVendor> outletVendors =
                                    XmlHelper.GetItems<XmlOutletVendor>(e.Result.Nodes[1], "Table").ToList();

                                // Delete data before insert 
                                _smartMobileContext.OutletVendor.DeleteAllOnSubmit(_smartMobileContext.OutletVendor.ToList());
                                _smartMobileContext.SubmitChanges();

                                OutletVendor localObject = null;

                                // converts to savable object-list
                                foreach (XmlOutletVendor item in outletVendors)
                                {
                                    localObject = new OutletVendor
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        OutletVendorKey = item.OutletVendorKey,
                                        OutletVendorName = item.OutletVendorName,
                                        Active = item.Active,
                                        OutltVendorType = item.OutltVendorType
                                    };

                                    _smartMobileContext.OutletVendor.InsertOnSubmit(localObject);
                                }

                                _smartMobileContext.SubmitChanges();
                                _currentType = ReaderWithoutWhereType.OutdoorType;
                                this.Proxy.GetReaderwhithoutewhereAsync("", "1", "OutdoorType", "");
                                break;
                            }

                        case ReaderWithoutWhereType.OutdoorType:
                            {
                                List<XmlOutDoorType> outDoorTypes =
                                    XmlHelper.GetItems<XmlOutDoorType>(e.Result.Nodes[1], "Table").ToList();

                                // Delete data before insert 
                                _smartMobileContext.OutDoorType.DeleteAllOnSubmit(_smartMobileContext.OutDoorType.ToList());
                                _smartMobileContext.SubmitChanges();

                                OutDoorType localObject = null;

                                // converts to savable object-list
                                foreach (XmlOutDoorType item in outDoorTypes)
                                {
                                    localObject = new OutDoorType
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        OutDoorTypeCode = item.OutDoorTypeCode,
                                        Description = item.Description,
                                        Active = item.Active
                                    };

                                    _smartMobileContext.OutDoorType.InsertOnSubmit(localObject);
                                }

                                _smartMobileContext.SubmitChanges();
                                _currentType = ReaderWithoutWhereType.InDoorType;
                                this.Proxy.GetReaderwhithoutewhereAsync("", "1", "InDoorType", "");
                                break;
                            }

                        case ReaderWithoutWhereType.InDoorType:
                            {
                                List<XmlInDoorType> inDoorTypes =
                                    XmlHelper.GetItems<XmlInDoorType>(e.Result.Nodes[1], "Table").ToList();

                                // Delete data before insert 
                                _smartMobileContext.InDoorType.DeleteAllOnSubmit(_smartMobileContext.InDoorType.ToList());
                                _smartMobileContext.SubmitChanges();


                                InDoorType localObject = null;

                                // converts to savable object-list
                                foreach (XmlInDoorType item in inDoorTypes)
                                {
                                    localObject = new InDoorType
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        InDoorTypeCode = item.OutDoorTypeCode,
                                        Description = item.Description,
                                        Active = item.Active
                                    };

                                    _smartMobileContext.InDoorType.InsertOnSubmit(localObject);
                                }

                                _smartMobileContext.SubmitChanges();
                                _currentType = ReaderWithoutWhereType.NokiaMerchandisingType;
                                this.Proxy.GetReaderwhithoutewhereAsync("", "1", "OutletNokiaMerchandisingType", "");
                                break;
                            }

                        case ReaderWithoutWhereType.NokiaMerchandisingType:
                            {
                                List<XmlNokiaMerchandisingType> nokiaMerchandisingTypes =
                                    XmlHelper.GetItems<XmlNokiaMerchandisingType>(e.Result.Nodes[1], "Table").ToList();

                                // Delete data before insert 
                                _smartMobileContext.OutletNokiaMerchandisingType.DeleteAllOnSubmit(
                                    _smartMobileContext.OutletNokiaMerchandisingType.ToList());
                                _smartMobileContext.SubmitChanges();

                                OutletNokiaMerchandisingType localObject = null;

                                // converts to savable object-list
                                foreach (XmlNokiaMerchandisingType item in nokiaMerchandisingTypes)
                                {
                                    localObject = new OutletNokiaMerchandisingType
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        Description = item.Description,
                                        IsFixFurnuture = item.IsFixFurnuture,
                                        Active = item.Active,
                                        MerchandisingCode = item.MerchandisingCode
                                    };

                                    _smartMobileContext.OutletNokiaMerchandisingType.InsertOnSubmit(localObject);
                                }

                                _smartMobileContext.SubmitChanges();
                                _currentType = ReaderWithoutWhereType.NokiaPG;
                                this.Proxy.GetReaderwhithoutewhereAsync("", "1", "NokiaPG", "");
                                break;
                            }

                        case ReaderWithoutWhereType.NokiaPG:
                            {
                                List<XmlNokiaPG> nokiaPgs =
                                    XmlHelper.GetItems<XmlNokiaPG>(e.Result.Nodes[1], "Table").ToList();

                                // Delete data before insert 
                                _smartMobileContext.NokiaPG.DeleteAllOnSubmit(_smartMobileContext.NokiaPG.ToList());
                                _smartMobileContext.SubmitChanges();

                                NokiaPG localObject = null;

                                // converts to savable object-list
                                foreach (XmlNokiaPG item in nokiaPgs)
                                {
                                    if (item.PGCode != null && item.PGCode.Length <= 10)
                                    {
                                        localObject = new NokiaPG
                                        {
                                            ID_PK = Guid.NewGuid(),
                                            PGCode = item.PGCode,
                                            PGType = item.PGType,
                                            Age = item.Age,
                                            Email = item.Email,
                                            PGName = item.PGName,
                                            Phone = item.Phone,
                                            ProvinceCode = item.ProvinceCode,
                                            Sex = item.Sex,
                                            TownCode = item.TownCode
                                        };

                                        _smartMobileContext.NokiaPG.InsertOnSubmit(localObject);
                                    }
                                }

                                _smartMobileContext.SubmitChanges();
                                _currentType = ReaderWithoutWhereType.OutletAdvanceInforListing;
                                this.Proxy.GetReaderwhithoutewhereAsync("", "1", "OutletAdvanceInforListing", "");
                                break;
                            }

                        case ReaderWithoutWhereType.OutletAdvanceInforListing:
                            {
                                List<XmlOutletAdvanceInforListing> outletAdvancePgs =
                                    XmlHelper.GetItems<XmlOutletAdvanceInforListing>(e.Result.Nodes[1], "Table").ToList();

                                // Delete data before insert 
                                _smartMobileContext.OutletAdvanceInforListing.DeleteAllOnSubmit(_smartMobileContext.OutletAdvanceInforListing.ToList());
                                _smartMobileContext.SubmitChanges();

                                OutletAdvanceInforListing localObject = null;

                                // converts to savable object-list
                                foreach (XmlOutletAdvanceInforListing item in outletAdvancePgs)
                                {
                                    localObject = new OutletAdvanceInforListing
                                    {
                                        ID_FK = Guid.NewGuid(),
                                        DataTable = item.DataTable,
                                        InforName = item.InforName,
                                        IsShow = Convert.ToBoolean(item.IsShow),
                                        ShowOrder = Convert.ToInt32(item.ShowOrder)
                                    };

                                    _smartMobileContext.OutletAdvanceInforListing.InsertOnSubmit(localObject);
                                }

                                _smartMobileContext.SubmitChanges();
                                _currentType = ReaderWithoutWhereType.OutletAdvanceInforTable;
                                this.Proxy.GetReaderwhithoutewhereAsync("", "1", "OutletAdvanceInforTable", "");
                                break;
                            }

                        case ReaderWithoutWhereType.OutletAdvanceInforTable:
                            {
                                List<XmlOutletAdvanceInforTable> outletAdvancePgs =
                                    XmlHelper.GetItems<XmlOutletAdvanceInforTable>(e.Result.Nodes[1], "Table").ToList();

                                // Delete data before insert 
                                _smartMobileContext.OutletAdvanceInforTable.DeleteAllOnSubmit(_smartMobileContext.OutletAdvanceInforTable.ToList());
                                _smartMobileContext.SubmitChanges();

                                OutletAdvanceInforTable localObject = null;

                                // converts to savable object-list
                                foreach (XmlOutletAdvanceInforTable item in outletAdvancePgs)
                                {
                                    localObject = new OutletAdvanceInforTable
                                    {
                                        ID_FK = Guid.NewGuid(),
                                        DataTable = item.DataTable,
                                        FieldName = item.FieldName,
                                        FieldShow = item.FieldShow,
                                        FieldShowOrder = Convert.ToInt32(item.FieldShowOrder),
                                        IsIndex = Convert.ToBoolean(item.IsIndex),
                                        IsPicture = Convert.ToBoolean(item.IsPicture),
                                        LinkFieldData = item.LinkFieldData,
                                        LinkFieldShow = item.LinkFieldShow,
                                        LinkTable = item.LinkTable
                                    };

                                    _smartMobileContext.OutletAdvanceInforTable.InsertOnSubmit(localObject);
                                }

                                _smartMobileContext.SubmitChanges();
                                _currentType = ReaderWithoutWhereType.END;

                                break;
                            }
                    }

                    ////if (_currentType == ReaderWithoutWhereType.END)
                    ////{
                        CheckBusyForGetOtherService();
                    ////}
                }
                catch
                {
                    base.IsBusy = false;
                    MessageBox.Show("Có lỗi xảy ra trong quá trình đồng bộ dữ liệu.\n Vui lòng thử lại sau");
                }
            }
            else
            {
                base.IsBusy = false;
                MessageBox.Show("Có lỗi xảy ra trong quá trình đồng bộ dữ liệu.\n Vui lòng thử lại sau");
            }
        }

        private void Proxy_GetReaderwhithwhereCompleted(object sender, GetReaderwhithwhereCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                try
                {
                    switch (_currentWithWhereType)
                    {
                        case ReaderWithWhereFieldType.ImageType:
                            List<XmlImageType> imageTypeList = XmlHelper.GetItems<XmlImageType>(e.Result.Nodes[1], "Table").ToList();

                            // Delete data before insert 
                            _smartMobileContext.IMAGETYPE.DeleteAllOnSubmit(_smartMobileContext.IMAGETYPE.ToList());
                            _smartMobileContext.SubmitChanges();

                            IMAGETYPE localImageType = null;

                            // converts to savable object-list
                            foreach (XmlImageType image in imageTypeList)
                            {
                                localImageType = new IMAGETYPE
                                {
                                    ID = image.Type,
                                    Description = image.DesCription,
                                    ID_PK = Guid.NewGuid()
                                    ////GROUP = image.grou,
                                    ////Status = image.Status,
                                };

                                _smartMobileContext.IMAGETYPE.InsertOnSubmit(localImageType);
                            }

                            _smartMobileContext.SubmitChanges();

                            GlobalInformation.ReportImageTypes = _smartMobileContext.IMAGETYPE.ToList();

                            this._getReaderwhithwhereCompleted = true;
                            _currentWithWhereType = ReaderWithWhereFieldType.City;
                            this.Proxy.GetReaderwhithwhereAsync("", "1", "City", "active = 1");
                            break;
                        case ReaderWithWhereFieldType.City:
                            List<XmlCity> cities = XmlHelper.GetItems<XmlCity>(e.Result.Nodes[1], "Table").ToList();

                            // Delete data before insert 
                            _smartMobileContext.City.DeleteAllOnSubmit(_smartMobileContext.City.ToList());
                            _smartMobileContext.SubmitChanges();

                            City localObject = null;

                            foreach (XmlCity item in cities)
                            {
                                localObject = new City
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        CityCode = item.CityCode,
                                        Description = item.Description
                                    };

                                _smartMobileContext.City.InsertOnSubmit(localObject);
                            }

                            _smartMobileContext.SubmitChanges();
                            _currentWithWhereType = ReaderWithWhereFieldType.Area;
                            this.Proxy.GetReaderwhithwhereAsync("", "1", "Area", "active = 1");
                            break;

                        case ReaderWithWhereFieldType.Area:
                            List<XmlArea> items = XmlHelper.GetItems<XmlArea>(e.Result.Nodes[1], "Table").ToList();

                            // Delete data before insert 
                            _smartMobileContext.Area.DeleteAllOnSubmit(_smartMobileContext.Area.ToList());
                            _smartMobileContext.SubmitChanges();

                            Area area = null;

                            foreach (XmlArea item in items)
                            {
                                area = new Area
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        AreaCode = item.AreaCode,
                                        Description = item.Description
                                    };

                                _smartMobileContext.Area.InsertOnSubmit(area);
                            }

                            _smartMobileContext.SubmitChanges();
                            _currentWithWhereType = ReaderWithWhereFieldType.GFKArea;
                            this.Proxy.GetReaderwhithwhereAsync("", "1", "GFKArea", "active = 1");
                            break;

                        case ReaderWithWhereFieldType.GFKArea:
                            List<XmlGFKArea> itemsGFKArea = XmlHelper.GetItems<XmlGFKArea>(e.Result.Nodes[1], "Table").ToList();

                            // Delete data before insert 
                            _smartMobileContext.GFKArea.DeleteAllOnSubmit(_smartMobileContext.GFKArea.ToList());
                            _smartMobileContext.SubmitChanges();

                            GFKArea gfkArea = null;

                            foreach (XmlGFKArea item in itemsGFKArea)
                            {
                                gfkArea = new GFKArea
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        GFKAreaCode = item.GFKAreaCode,
                                        Description = item.Description
                                    };

                                _smartMobileContext.GFKArea.InsertOnSubmit(gfkArea);
                            }

                            _smartMobileContext.SubmitChanges();
                            _currentWithWhereType = ReaderWithWhereFieldType.Operators;
                            this.Proxy.GetReaderwhithwhereAsync("", "1", "PhoneVendor", "Active=1 and IsOperator=1");
                            break;

                        case ReaderWithWhereFieldType.Operators:
                            List<XmlPhoneVendor> itemsOperators = XmlHelper.GetItems<XmlPhoneVendor>(e.Result.Nodes[1], "Table").ToList();

                            // Delete data before insert 
                            _smartMobileContext.PhoneVendor.DeleteAllOnSubmit(_smartMobileContext.PhoneVendor.ToList());
                            _smartMobileContext.SubmitChanges();

                            PhoneVendor phoneVendor = null;

                            foreach (XmlPhoneVendor item in itemsOperators)
                            {
                                phoneVendor = new PhoneVendor
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        PhoneVendorCode = item.PhoneVendorCode,
                                        PhoneVendorName = item.PhoneVendorName
                                    };

                                _smartMobileContext.PhoneVendor.InsertOnSubmit(phoneVendor);
                            }

                            _smartMobileContext.SubmitChanges();

                            _currentWithWhereType = ReaderWithWhereFieldType.Region;
                            this.Proxy.GetReaderwhithwhereAsync("", "1", "Region", "Active=1");
                            break;

                        case ReaderWithWhereFieldType.Region:
                            List<XmlRegion> itemsRegion = XmlHelper.GetItems<XmlRegion>(e.Result.Nodes[1], "Table").ToList();

                            // Delete data before insert 
                            _smartMobileContext.Region.DeleteAllOnSubmit(_smartMobileContext.Region.ToList());
                            _smartMobileContext.SubmitChanges();

                            Region region = null;

                            foreach (XmlRegion item in itemsRegion)
                            {
                                region = new Region
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        RegionCode = item.RegionCode,
                                        Description = item.Description
                                    };

                                _smartMobileContext.Region.InsertOnSubmit(region);
                            }

                            _smartMobileContext.SubmitChanges();
                            _currentWithWhereType = ReaderWithWhereFieldType.Tier;
                            this.Proxy.GetReaderwhithwhereAsync("", "1", "Tier", "Active=1");
                            break;

                        case ReaderWithWhereFieldType.Tier:
                            List<XmlTier> itemsTier = XmlHelper.GetItems<XmlTier>(e.Result.Nodes[1], "Table").ToList();

                            // Delete data before insert 
                            _smartMobileContext.Tier.DeleteAllOnSubmit(_smartMobileContext.Tier.ToList());
                            _smartMobileContext.SubmitChanges();

                            Tier tier = null;

                            foreach (XmlTier item in itemsTier)
                            {
                                tier = new Tier
                                    {
                                        ID_PK = Guid.NewGuid(),
                                        TierCode = item.TierCode,
                                        Description = item.Description
                                    };

                                _smartMobileContext.Tier.InsertOnSubmit(tier);
                            }

                            _smartMobileContext.SubmitChanges();
                            _currentWithWhereType = ReaderWithWhereFieldType.END;
                            break;

                        default:
                            break;
                    }

                    ////if (_currentWithWhereType == ReaderWithWhereFieldType.END)
                    ////{
                        CheckBusyForGetOtherService();
                    ////}
                }
                catch
                {
                    base.IsBusy = false;
                    MessageBox.Show("Có lỗi xảy ra trong quá trình đồng bộ dữ liệu.\n Vui lòng thử lại sau");
                }
            }
            else
            {
                base.IsBusy = false;
                MessageBox.Show("Có lỗi xảy ra trong quá trình đồng bộ dữ liệu.\n Vui lòng thử lại sau");
            }
        }

        private void Proxy_GetTownCompleted(object sender, GetTownCompletedEventArgs e)
        {
            try
            {
                _smartMobileContext.CreateIfNotExists();

                List<XmlTown> townList = XmlHelper.GetItems<XmlTown>(e.Result.Nodes[1], "Table").ToList();

                // Delete data before insert 
                _smartMobileContext.TOWN.DeleteAllOnSubmit(_smartMobileContext.TOWN.ToList());
                _smartMobileContext.SubmitChanges();

                TOWN town = null;

                // converts to savable object-list
                foreach (XmlTown item in townList)
                {
                    town = new TOWN
                    {
                        ID_PK = Guid.NewGuid(),
                        ProvinceKey = item.ProvinceCode,
                        Townkey = item.TownCode,
                        TownName = item.TownName
                    };

                    _smartMobileContext.TOWN.InsertOnSubmit(town);
                }

                _smartMobileContext.SubmitChanges();

                this._getTownCompleted = true;

                this.CheckBusy();
            }
            catch (Exception)
            {
                this.IsBusy = false;
                this.UpdateCommand.RaiseCanExecuteChanged(true);
                throw;
            }
        }

        private void Proxy_GetProvinceCompleted(object sender, GetProvinceCompletedEventArgs e)
        {
            try
            {
                _smartMobileContext.CreateIfNotExists();

                List<XmlProvince> provinceList = XmlHelper.GetItems<XmlProvince>(e.Result.Nodes[1], "Table").ToList();

                // Delete data before insert 
                _smartMobileContext.PROVINCE.DeleteAllOnSubmit(_smartMobileContext.PROVINCE.ToList());
                _smartMobileContext.SubmitChanges();

                PROVINCE province = null;

                // converts to savable object-list
                foreach (XmlProvince item in provinceList)
                {
                    province = new PROVINCE
                    {
                        ID_PK = Guid.NewGuid(),
                        ProvinceKey = item.ProvinceCode,
                        ProvinceName = item.ProvinceName
                    };

                    _smartMobileContext.PROVINCE.InsertOnSubmit(province);
                }

                _smartMobileContext.SubmitChanges();

                this._getProvinceCompleted = true;

                this.CheckBusy();
            }
            catch (Exception)
            {
                this.IsBusy = false;
                this.UpdateCommand.RaiseCanExecuteChanged(true);
                throw;
            }
        }

        #endregion

        private void CheckBusy()
        {
            if (this._checkBusy < this._progress)
            {
                this._checkBusy += 1;
            }
            else
            {
                if (!this._isOnGettingCustomer)
                {
                    this.IsBusy = false;
                    this.UpdateCommand.RaiseCanExecuteChanged(true);
                    MessageBox.Show("Đồng bộ dữ liệu về máy thành công.");
                    base.PageNavigation.Navigate("Main");
                }
                else
                {
                    _currentType = ReaderWithoutWhereType.PhoneVendor;
                    this.Proxy.GetReaderwhithoutewhereAsync("", "1", "PhoneVendor", "");
                }
            }
        }

        private void CheckBusyForGetOtherService()
        {
            if (this._currentType == ReaderWithoutWhereType.END && _currentWithWhereType == ReaderWithWhereFieldType.END)
            {
                this.IsBusy = false;
                this.UpdateCommand.RaiseCanExecuteChanged(true);
                MessageBox.Show("Đồng bộ dữ liệu về máy thành công.");
                base.PageNavigation.Navigate("Main");
            }
            //else
            //{
            //    if (this._currentType == ReaderWithoutWhereType.END)
            //    {
            //        _currentType = ReaderWithoutWhereType.PhoneVendor;
            //        this.Proxy.GetReaderwhithoutewhereAsync("", "1", "PhoneVendor", "");
            //        this._currentType = ReaderWithoutWhereType.FINISH;
            //    }
            //}
        }
    }
}
